// React核心库导入
import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
// 对话服务导入
import conversationService, {
  ConversationDto,
  ConversationDetailDto,
  ConversationMessageDto,
  CreateConversationInput,
  UpdateConversationInput,
  AddMessageInput,
  UpdateMessageInput,
  ConversationStatisticsDto,
  ConversationStatus,
  GetConversationListInput
} from '@services/conversationService';
// 消息提示组件导入
import { message } from 'antd';

// 对话状态接口
interface ConversationState {
  // 对话列表数据
  conversations: ConversationDto[];
  // 当前对话详情
  currentConversation: ConversationDetailDto | null;
  // 加载状态
  loading: boolean;
  // 错误信息
  error: string | null;
  // 总数统计
  totalCount: number;
  // 过滤条件
  filters: GetConversationListInput;
  // 统计信息
  statistics: ConversationStatisticsDto | null;
}

// 对话动作类型
type ConversationAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_CONVERSATIONS'; payload: { conversations: ConversationDto[]; totalCount: number } }
  | { type: 'SET_CURRENT_CONVERSATION'; payload: ConversationDetailDto | null }
  | { type: 'ADD_CONVERSATION'; payload: ConversationDto }
  | { type: 'UPDATE_CONVERSATION'; payload: ConversationDto }
  | { type: 'DELETE_CONVERSATION'; payload: string }
  | { type: 'SET_FILTERS'; payload: Partial<GetConversationListInput> }
  | { type: 'SET_STATISTICS'; payload: ConversationStatisticsDto }
  | { type: 'ADD_MESSAGE'; payload: { conversationId: string; message: ConversationMessageDto } }
  | { type: 'UPDATE_MESSAGE'; payload: { conversationId: string; message: ConversationMessageDto } }
  | { type: 'DELETE_MESSAGE'; payload: { conversationId: string; messageId: string } };

// 初始状态
const initialState: ConversationState = {
  conversations: [],
  currentConversation: null,
  loading: false,
  error: null,
  totalCount: 0,
  filters: {
    skipCount: 0,
    maxResultCount: 10,
    sorting: 'lastMessageAt desc'
  },
  statistics: null
};

// Reducer函数
function conversationReducer(state: ConversationState, action: ConversationAction): ConversationState {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };

    case 'SET_CONVERSATIONS':
      return {
        ...state,
        conversations: action.payload.conversations,
        totalCount: action.payload.totalCount,
        loading: false,
        error: null
      };

    case 'SET_CURRENT_CONVERSATION':
      return { ...state, currentConversation: action.payload, loading: false };

    case 'ADD_CONVERSATION':
      return {
        ...state,
        conversations: [action.payload, ...state.conversations],
        totalCount: state.totalCount + 1
      };

    case 'UPDATE_CONVERSATION':
      return {
        ...state,
        conversations: state.conversations.map(conv =>
          conv.id === action.payload.id ? action.payload : conv
        ),
        currentConversation:
          state.currentConversation?.id === action.payload.id
            ? { ...state.currentConversation, ...action.payload }
            : state.currentConversation
      };

    case 'DELETE_CONVERSATION':
      return {
        ...state,
        conversations: state.conversations.filter(conv => conv.id !== action.payload),
        currentConversation:
          state.currentConversation?.id === action.payload ? null : state.currentConversation,
        totalCount: state.totalCount - 1
      };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: { ...state.filters, ...action.payload }
      };

    case 'SET_STATISTICS':
      return { ...state, statistics: action.payload };

    case 'ADD_MESSAGE':
      const { conversationId: addConvId, message: addedMessage } = action.payload;
      const updatedConversationsForAdd = state.conversations.map(conv =>
        conv.id === addConvId
          ? {
              ...conv,
              messageCount: conv.messageCount + 1,
              lastMessageAt: addedMessage.createdAt
            }
          : conv
      );

      let updatedCurrentForAdd = state.currentConversation;
      if (state.currentConversation?.id === addConvId) {
        updatedCurrentForAdd = {
          ...state.currentConversation,
          messageCount: state.currentConversation.messageCount + 1,
          lastMessageAt: addedMessage.createdAt,
          messages: [...state.currentConversation.messages, addedMessage]
        };
      }

      return {
        ...state,
        conversations: updatedConversationsForAdd,
        currentConversation: updatedCurrentForAdd
      };

    case 'UPDATE_MESSAGE':
      const { conversationId: updateConvId, message: updatedMessage } = action.payload;
      let updatedCurrentForUpdate = state.currentConversation;
      if (state.currentConversation?.id === updateConvId) {
        updatedCurrentForUpdate = {
          ...state.currentConversation,
          messages: state.currentConversation.messages.map(msg =>
            msg.id === updatedMessage.id ? updatedMessage : msg
          )
        };
      }

      return {
        ...state,
        currentConversation: updatedCurrentForUpdate
      };

    case 'DELETE_MESSAGE':
      const { conversationId: deleteConvId, messageId } = action.payload;
      let updatedCurrentForDelete = state.currentConversation;
      if (state.currentConversation?.id === deleteConvId) {
        updatedCurrentForDelete = {
          ...state.currentConversation,
          messageCount: state.currentConversation.messageCount - 1,
          messages: state.currentConversation.messages.filter(msg => msg.id !== messageId)
        };
      }

      return {
        ...state,
        currentConversation: updatedCurrentForDelete
      };

    default:
      return state;
  }
}

// Context创建
const ConversationContext = createContext<{
  state: ConversationState;
  actions: {
    fetchConversations: () => void;
    fetchConversationDetail: (id: string) => void;
    createConversation: (input: CreateConversationInput) => Promise<void>;
    updateConversation: (id: string, input: UpdateConversationInput) => Promise<void>;
    deleteConversation: (id: string) => Promise<void>;
    addMessage: (conversationId: string, input: AddMessageInput) => Promise<void>;
    updateMessage: (messageId: string, input: UpdateMessageInput) => Promise<void>;
    deleteMessage: (messageId: string) => Promise<void>;
    fetchStatistics: (agentId?: string) => void;
    closeConversation: (id: string) => Promise<void>;
    reopenConversation: (id: string) => Promise<void>;
    setFilters: (filters: Partial<GetConversationListInput>) => void;
    resetFilters: () => void;
  };
} | null>(null);

// Provider组件
interface ConversationProviderProps {
  children: ReactNode;
}

export const ConversationProvider: React.FC<ConversationProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(conversationReducer, initialState);

  // 获取对话列表
  const fetchConversations = async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const { items, totalCount } = await conversationService.getConversationList(state.filters);
      dispatch({ type: 'SET_CONVERSATIONS', payload: { conversations: items, totalCount } });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取对话列表失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 获取对话详情
  const fetchConversationDetail = async (id: string) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const conversation = await conversationService.getConversationDetail(id);
      dispatch({ type: 'SET_CURRENT_CONVERSATION', payload: conversation });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取对话详情失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 创建对话
  const createConversation = async (input: CreateConversationInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const conversation = await conversationService.createConversation(input);
      dispatch({ type: 'ADD_CONVERSATION', payload: conversation });
      message.success('对话创建成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建对话失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 更新对话
  const updateConversation = async (id: string, input: UpdateConversationInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const conversation = await conversationService.updateConversation(id, input);
      dispatch({ type: 'UPDATE_CONVERSATION', payload: conversation });
      message.success('对话更新成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新对话失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 删除对话
  const deleteConversation = async (id: string) => {
    try {
      await conversationService.deleteConversation(id);
      dispatch({ type: 'DELETE_CONVERSATION', payload: id });
      message.success('对话删除成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除对话失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 添加消息
  const addMessage = async (conversationId: string, input: AddMessageInput) => {
    try {
      const message = await conversationService.addMessage(conversationId, input);
      dispatch({ type: 'ADD_MESSAGE', payload: { conversationId, message } });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '添加消息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 更新消息
  const updateMessage = async (messageId: string, input: UpdateMessageInput) => {
    try {
      const message = await conversationService.updateMessage(messageId, input);
      const conversationId = state.currentConversation?.id;
      if (conversationId) {
        dispatch({ type: 'UPDATE_MESSAGE', payload: { conversationId, message } });
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新消息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 删除消息
  const deleteMessage = async (messageId: string) => {
    try {
      await conversationService.deleteMessage(messageId);
      const conversationId = state.currentConversation?.id;
      if (conversationId) {
        dispatch({ type: 'DELETE_MESSAGE', payload: { conversationId, messageId } });
      }
      message.success('消息删除成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除消息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 获取统计信息
  const fetchStatistics = async (agentId?: string) => {
    try {
      const statistics = await conversationService.getConversationStatistics(agentId);
      dispatch({ type: 'SET_STATISTICS', payload: statistics });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取统计信息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 关闭对话
  const closeConversation = async (id: string) => {
    try {
      await conversationService.closeConversation(id);
      // 更新对话状态
      const conversation = state.conversations.find(c => c.id === id);
      if (conversation) {
        dispatch({
          type: 'UPDATE_CONVERSATION',
          payload: { ...conversation, status: ConversationStatus.Closed }
        });
      }
      message.success('对话已关闭');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '关闭对话失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 重新打开对话
  const reopenConversation = async (id: string) => {
    try {
      await conversationService.reopenConversation(id);
      // 更新对话状态
      const conversation = state.conversations.find(c => c.id === id);
      if (conversation) {
        dispatch({
          type: 'UPDATE_CONVERSATION',
          payload: { ...conversation, status: ConversationStatus.Active }
        });
      }
      message.success('对话已重新打开');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '重新打开对话失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 设置过滤条件
  const setFilters = (filters: Partial<GetConversationListInput>) => {
    dispatch({ type: 'SET_FILTERS', payload: filters });
  };

  // 重置过滤条件
  const resetFilters = () => {
    dispatch({
      type: 'SET_FILTERS',
      payload: {
        skipCount: 0,
        maxResultCount: 10,
        sorting: 'lastMessageAt desc'
      }
    });
  };

  // 监听过滤条件变化，自动刷新数据
  useEffect(() => {
    fetchConversations();
  }, [state.filters]);

  // 获取统计信息
  useEffect(() => {
    fetchStatistics();
  }, []);

  const actions = {
    fetchConversations,
    fetchConversationDetail,
    createConversation,
    updateConversation,
    deleteConversation,
    addMessage,
    updateMessage,
    deleteMessage,
    fetchStatistics,
    closeConversation,
    reopenConversation,
    setFilters,
    resetFilters
  };

  return (
    <ConversationContext.Provider value={{ state, actions }}>
      {children}
    </ConversationContext.Provider>
  );
};

// Hook函数
export const useConversation = () => {
  const context = useContext(ConversationContext);
  if (!context) {
    throw new Error('useConversation must be used within a ConversationProvider');
  }
  return context;
};

// 选择器Hook
export const useConversations = () => {
  const { state } = useConversation();
  return state.conversations;
};

export const useConversationLoading = () => {
  const { state } = useConversation();
  return state.loading;
};

export const useConversationError = () => {
  const { state } = useConversation();
  return state.error;
};

export const useConversationFilters = () => {
  const { state, actions } = useConversation();
  return {
    filters: state.filters,
    setFilters: actions.setFilters,
    resetFilters: actions.resetFilters
  };
};

export const useCurrentConversation = () => {
  const { state } = useConversation();
  return state.currentConversation;
};

export const useConversationStatistics = () => {
  const { state, actions } = useConversation();
  return {
    statistics: state.statistics,
    fetchStatistics: actions.fetchStatistics
  };
};